//获取数据，渲染数据
const creator='qwerty'

function getBooksList(){
    axios({
        url:"http://hmajax.itheima.net/api/books",
        params:{
            creator
        }
    }).then(result=>{
        const bookList=result.data.data
        console.log(bookList);
        const htmlStr=bookList.map((item,index)=>{
            return `<tr>
            <td>${index+1}</td>
          <td>${item.bookname}</td>
          <td>${item.author}</td>
          <td>${item.publisher}</td>
          <td data-id=${item.id}>
            <span class="del">删除</span>
            <span class="edit">编辑</span>
          </td>
          <tr>`
        }).join('')
        document.querySelector('.list').innerHTML=htmlStr
    })
}



getBooksList()

// 新增图书
const addModalDom = document.querySelector('.add-modal')
const addModal = new bootstrap.Modal(addModalDom)
document.querySelector('.add-btn').addEventListener('click', () => {
    const addForm = document.querySelector('.add-form')
    const bookObj = serialize(addForm, { hash: true, empty: true })
    // console.log(bookObj);
    
    axios({
        url: "http://hmajax.itheima.net/api/books",
        method: 'POST',
        data: {
            ...bookObj,
            creator
        }
    }).then(() => {

        getBooksList()
        addForm.reset()
        addModal.hide()
    })

})

// 删除图书
document.querySelector('.list').addEventListener('click',e=>{
    if(e.target.classList.contains('del')){
        theId=e.target.parentNode.dataset.id
        axios({
        url: `http://hmajax.itheima.net/api/books/${theId}`,
        method:'DELETE'
        
        }).then(()=>{
        getBooksList()

        })

    }
    
})

// 编辑图书
const editDom=document.querySelector('.edit-modal')
const editModal=new bootstrap.Modal(editDom)
document.querySelector('.list').addEventListener('click',e=>{
    
    if(e.target.classList.contains('edit')){
        theId=e.target.parentNode.dataset.id
        axios({
            url: `http://hmajax.itheima.net/api/books/${theId}`,
            
        }).then(result=>{
            const bookObj=result.data.data
            document.querySelector('.edit-form .bookname').value=bookObj.bookname
            document.querySelector('.edit-form .author').value=bookObj.author
            document.querySelector('.edit-form .publisher').value=bookObj.publisher
        })
        editModal.show()
    }
})

document.querySelector('.edit-btn').addEventListener('click',()=>{
    const editForm=document.querySelector('.edit-form')
    const bookObj=serialize(editForm,{hash:true,empty:true})
    
    
    axios({
        url: `http://hmajax.itheima.net/api/books/${theId}`,
        method:'PUT',
        data:{
            ...bookObj,
            creator

        }
    }).then(()=>{
        getBooksList()

    })
    // getBooksList()


    editModal.hide()
})